package com.cloudfun.campusshare.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cloudfun.campusshare.entity.RegionEntity;
import com.cloudfun.campusshare.repo.sql.SqlRegion;
import com.cloudfun.campusshare.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RegionServiceImpl implements RegionService {
    @Autowired
    private EntityManager entityManager;

    @Override
    public List<RegionEntity> getRegion(String provinceCode, String cityCode) {
        String sql;
        if (StringUtils.isEmpty(provinceCode) && StringUtils.isEmpty(cityCode)) {
            sql = SqlRegion.PROVINCES;
        } else if (provinceCode != null && cityCode == null) {
            sql = StrUtil.format(SqlRegion.CITYS,provinceCode);
        }else {
            sql =StrUtil.format(SqlRegion.AREAS,cityCode);
        }
        Query nativeQuery = entityManager.createNativeQuery(sql);
        List<Object[]> resultList = nativeQuery.getResultList();
        return resultList.stream().map(va->{
            RegionEntity regionEntity= new RegionEntity();
            regionEntity.setCode(va[0].toString());
            regionEntity.setName(va[1].toString());
            return regionEntity;
        }).collect(Collectors.toList());
    }
}
